package com.sojson.util.xml.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sojson.constant.Constant;
import com.sojson.util.StringUtil;
import com.sojson.util.file.FileUtil;
import com.sojson.util.xml.XmlUtilInterface;

import lombok.extern.slf4j.Slf4j;

/**
 * Xml工具类实现类
 * 
 * @author liu
 * @date 2020-10-21
 */
@Slf4j
public class XmlUtilImpl implements XmlUtilInterface {

    private static XmlUtilImpl xmlUtilImpl;

    private XmlUtilImpl() {}

    /**
     * 将Xml格式字符串转为Map
     * 
     * @param data Xml格式字符串
     * @return
     * @throws Exception 
     */
    @Override
    public Map<String, String> xmlToMap(String data) throws Exception {
        Map<String, String> map = new HashMap<>(16);
        InputStream stream = null;

        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setExpandEntityReferences(false);
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            stream = new ByteArrayInputStream(data.getBytes());
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();

            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element)node;
                    map.put(element.getNodeName(), element.getTextContent());
                }
            }
        } finally {
            try {
                stream.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return map;
    }

    /**
     * 将Map转为Xml格式字符串
     * 
     * @param map Map集合
     * @return
     * @throws Exception 
     */
    @Override
    public String mapToXml(Map<String, Object> data) throws Exception {
        StringWriter writer = null;
        String output = null;

        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            org.w3c.dom.Document document = documentBuilder.newDocument();
            org.w3c.dom.Element root = document.createElement("xml");
            document.appendChild(root);
            for (String key : data.keySet()) {
                String value = data.get(key).toString();
                if (value == null) {
                    value = "";
                }
                value = value.trim();
                org.w3c.dom.Element filed = document.createElement(key);
                filed.appendChild(document.createTextNode(value));
                root.appendChild(filed);
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, Constant.DEFAULT_ENCODING);
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            // .replaceAll("\n|\r", "");
            output = writer.getBuffer().toString();
        } finally {
            closeStream(writer);
        }
        return output;
    }

    /**
     * 关闭字符输出流
     * 
     * @param reader 需要关闭的字符输出流
     * @throws IOException
     */
    private void closeStream(Writer writer) throws IOException {
        FileUtil.closeStream(writer);
    }

    /**
     * 判断一个对象是否是空(空对象)
     * 
     * @param obj
     * @return
     */
    private static boolean isBlankObject(Object obj) {
        return StringUtil.isBlankObject(obj);
    }

    public static XmlUtilImpl getInstances() {
        if (isBlankObject(xmlUtilImpl)) {
            xmlUtilImpl = new XmlUtilImpl();
        }
        return xmlUtilImpl;
    }

}